package com.glacier.framework.boot.context;

import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;

import java.util.Optional;

/**
 * date 2023-12-22 12:35
 * spring 容器帮助类
 *
 * @author glacier
 * @version 1.0
 */
public class ApplicationContextHelper implements ApplicationContextAware {
    @Getter
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        ApplicationContextHelper.applicationContext = applicationContext;
    }

    /**
     * 获取bean
     *
     * @param clz
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> clz) {
        return Optional.of(applicationContext.getBean(clz))
                .orElseGet(() -> (T) applicationContext.getBean(getSimpleBeanName(clz)));
    }


    /**
     * 获取bean
     *
     * @param clz
     * @return
     */
    public static Object getBean(String clz) {
        return applicationContext.getBean(clz);
    }

    /**
     * 获取bean
     *
     * @param name
     * @param requiredType
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> requiredType) {
        return applicationContext.getBean(name, requiredType);
    }

    /**
     * 获取bean
     *
     * @param requiredType
     * @param params
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> requiredType, Object... params) {
        return applicationContext.getBean(requiredType, params);
    }


    /**
     * 获取bean名称
     *
     * @param clz
     * @param <T>
     * @return
     */
    private static <T> String getSimpleBeanName(Class<T> clz) {
        String simpleName = clz.getSimpleName();
        return Character.toLowerCase(simpleName.charAt(0)) + simpleName.substring(1);
    }

}
